import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useCartStore = defineStore('cart', () => {
  // 状态
  const cartItems = ref(JSON.parse(localStorage.getItem('cartItems') || '[]'))

  // 计算属性
  const totalCount = computed(() => {
    return cartItems.value.reduce((total, item) => total + item.count, 0)
  })

  const totalPrice = computed(() => {
    return cartItems.value.reduce((total, item) => {
      return total + (item.price * item.count)
    }, 0)
  })

  const isEmpty = computed(() => {
    return cartItems.value.length === 0
  })

  const selectedItems = computed(() => {
    return cartItems.value.filter(item => item.selected)
  })

  const selectedCount = computed(() => {
    return selectedItems.value.reduce((total, item) => total + item.count, 0)
  })

  const selectedPrice = computed(() => {
    return selectedItems.value.reduce((total, item) => {
      return total + (item.price * item.count)
    }, 0)
  })

  // 方法
  function addToCart(product) {
    const existingItem = cartItems.value.find(item => item.id === product.id)
    
    if (existingItem) {
      existingItem.count += 1
    } else {
      cartItems.value.push({
        ...product,
        count: 1,
        selected: true
      })
    }
    
    saveToStorage()
  }

  function removeFromCart(productId) {
    const index = cartItems.value.findIndex(item => item.id === productId)
    if (index > -1) {
      cartItems.value.splice(index, 1)
      saveToStorage()
    }
  }

  function updateCount(productId, count) {
    const item = cartItems.value.find(item => item.id === productId)
    if (item) {
      if (count <= 0) {
        removeFromCart(productId)
      } else {
        item.count = count
        saveToStorage()
      }
    }
  }

  function toggleSelect(productId) {
    const item = cartItems.value.find(item => item.id === productId)
    if (item) {
      item.selected = !item.selected
      saveToStorage()
    }
  }

  function toggleSelectAll(selected) {
    cartItems.value.forEach(item => {
      item.selected = selected
    })
    saveToStorage()
  }

  function clearCart() {
    cartItems.value = []
    saveToStorage()
  }

  function clearSelected() {
    cartItems.value = cartItems.value.filter(item => !item.selected)
    saveToStorage()
  }

  // 添加商品到购物车（与微信小程序API保持一致）
  function addItem(newItem) {
    const { skuId, sku, count } = newItem
    
    // 查找是否已存在相同的SKU
    const existingItem = cartItems.value.find(item => item.skuId === skuId)
    
    if (existingItem) {
      // 如果已存在，增加数量
      existingItem.count += count
    } else {
      // 如果不存在，添加新项
      cartItems.value.push({
        skuId: skuId,
        id: sku.id,
        title: sku.title,
        img: sku.img,
        price: sku.actual_price || sku.price,
        count: count,
        selected: true,
        sku: sku // 保留完整的SKU信息
      })
    }
    
    saveToStorage()
    
    console.log('添加到购物车:', newItem)
    console.log('当前购物车:', cartItems.value)
  }

  function saveToStorage() {
    localStorage.setItem('cartItems', JSON.stringify(cartItems.value))
  }

  return {
    cartItems,
    totalCount,
    totalPrice,
    isEmpty,
    selectedItems,
    selectedCount,
    selectedPrice,
    addToCart,
    addItem, // 添加到返回对象
    removeFromCart,
    updateCount,
    toggleSelect,
    toggleSelectAll,
    clearCart,
    clearSelected
  }
}) 